package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 智能设备Service业务层处理
 *
 * @author alexis
 * @date 2025-06-01
 */
@Service
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Resource
    private IoTDAClient client;

    /**
     * 查询智能设备
     *
     * @param id 智能设备主键
     * @return 智能设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询智能设备列表
     *
     * @param device 智能设备
     * @return 智能设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);
    }

    /**
     * 新增智能设备
     *
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 修改智能设备
     *
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int updateDevice(Device device) {
        return deviceMapper.updateById(device);
    }

    /**
     * 批量删除智能设备
     *
     * @param ids 需要删除的智能设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除智能设备信息
     *
     * @param id 智能设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceById(Long id) {
        return deviceMapper.deleteById(id);
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {
        //请求参数
        ListProductsRequest request = new ListProductsRequest();

        //设置条数
        request.setLimit(50);

        //发起请求
        ListProductsResponse response = client.listProducts(request);
        if (response.getHttpStatusCode() != 200) {
            throw new BaseException("物联网接口 - 查询产品，同步失败");
        }

        //存储到redis
        redisTemplate.opsForValue().set(CacheConstants.IOT_ALL_PRODUCT_LIST, JSONUtil.toJsonStr(response.getProducts()));

    }

    /**
     * 查询所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        //从redis中查询数据
        String result = redisTemplate.opsForValue().get(CacheConstants.IOT_ALL_PRODUCT_LIST);

        //如果数据为空，则返回一个空集合
        if (StringUtils.isEmpty(result)) {
            return new ArrayList<>();
        }

        return JSONUtil.toList(result, ProductVo.class);
    }

    /**
     * 注册设备
     *
     * @param deviceDto
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //判断设备名称是否重复
        LambdaQueryWrapper<Device> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(Device::getDeviceName, deviceDto.getDeviceName());
        if (deviceMapper.selectCount(nameWrapper) > 0) {
            throw new BaseException("设备名称已存在，请重新输入");
        }

        //检验设备标识码是否重复
        LambdaQueryWrapper<Device> nodeIdWrapper = new LambdaQueryWrapper<>();
        nodeIdWrapper.eq(Device::getNodeId, deviceDto.getNodeId());
        if (deviceMapper.selectCount(nodeIdWrapper) > 0) {
            throw new BaseException("设备标识码已存在，请重新输入");
        }

        //校验同一位置是否绑定了同一类产品
        LambdaQueryWrapper<Device> condition = new LambdaQueryWrapper<>();
        condition.eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey());
        if (deviceMapper.selectCount(condition) > 0) {
            throw new BaseException("该老人/位置已绑定该产品，请重新选择");
        }

        //iot中新增设备
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withProductId(deviceDto.getProductKey());
        body.withDeviceName(deviceDto.getDeviceName());
        body.withNodeId(deviceDto.getNodeId());
        request.withBody(body);
        AuthInfo authInfo = new AuthInfo();

        //秘钥
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        authInfo.withSecret(secret);
        body.withAuthInfo(authInfo);
        AddDeviceResponse response;

        try {
            response = client.addDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 注册设备，调用失败");
        }

        //设备数据保存到数据库
        //属性拷贝
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);

        try {
            deviceMapper.insert(device);
        } catch (Exception e) {
            throw new BaseException("同一个位置不能绑定同类型的产品");
        }

    }

    /**
     * 获取设备详细信息
     *
     * @param iotId
     * @return
     */
    @Override
    public DeviceDetailVo getInfo(String iotId) {
        //查询数据库
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            return null;
        }
        //查询iot平台
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response;
        try {
            response = client.showDevice(request);
        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("物联网接口 - 查询设备详情，调用失败");
        }

        DeviceDetailVo detailVo = new DeviceDetailVo();
        BeanUtil.copyProperties(device, detailVo);
        detailVo.setDeviceStatus(response.getStatus());
        String activeTime = response.getActiveTime();

        if (StringUtils.isNotEmpty(activeTime)) {
            LocalDateTime time = toLocalDateTime(activeTime);
            detailVo.setActiveTime(time);

        }
        return detailVo;
    }

    public LocalDateTime toLocalDateTime(String activeTime) {
        LocalDateTime time = LocalDateTimeUtil.parse(activeTime, DatePattern.UTC_MS_PATTERN);
        time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        return time;
    }

    public LocalDateTime otherLocalDateTime(String activeTime) {
        LocalDateTime time = LocalDateTimeUtil.parse(activeTime, "yyyyMMdd'T'HHmmss'Z'");
        time = time.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        return time;
    }

    /**
     * 查看设备上报的数据
     *
     * @param iotId
     * @return
     */
    @Override
    public List<Map<String, Object>> queryServiceProperties(String iotId) {
        //通过client 调用查询设备影子数据
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.setDeviceId(iotId);
        ShowDeviceShadowResponse response = client.showDeviceShadow(request);

        //解析数据
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            return new ArrayList<>();
        }
        JSONObject jsonObject = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());

        String eventTimeStr = shadow.get(0).getReported().getEventTime();
        LocalDateTime time = otherLocalDateTime(eventTimeStr);

        //定义返回的结果
        List<Map<String, Object>> list = new ArrayList<>();
        jsonObject.forEach((key,value)->{
            Map<String,Object> map = new HashMap<>();
            map.put("functionId",key);
            map.put("value",value);
            map.put("eventTime",time);
            list.add(map);
        });
        return list;
    }

    /**
     * 查询产品详情(报警规则模块使用)
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProductAlertRule(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);

        ShowProductResponse response;
        try {
            response = client.showProduct(request);
        } catch (Exception e) {
            throw new BaseException("查询产品失败！");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        if (CollectionUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(new ArrayList<>());
        }

        return AjaxResult.success(serviceCapabilities);
    }
}
